package com.htzy.extrace.baidumap;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.htzy.extrace.loader.ExpressHistoryLoader;
import com.htzy.extrace.misc.model.HistoryGist;
import com.htzy.extrace.net.IDataAdapter;
import com.htzy.extrace.ui.main.MainActivity;
import com.htzy.extrace.ui.main.R;

/**
 * 百度地图：历史路径绘制
 * 
 * @author liujiangfeng
 *
 */
public class BaiduMapHistoryActivity extends Activity implements
		IDataAdapter<List<HistoryGist>> {
	private MapView mMapView;
	private BaiduMap mBaiduMap;

	private Intent mIntent;
	private ExpressHistoryLoader mLoader;
	private List<HistoryGist> historyGists;
	private float latitude;
	private float longtitude;

	LatLng latlng;
	List<LatLng> latLngPolygon;

	private Context context;

	// 定位相关
	private LocationClient mLocationClient;
	private MyLocationListener mLocationListener;
	private boolean isFirstIn = true;
	// 自定义定位图标
	private BitmapDescriptor mIconLocation;
	private float mCurrentX;
	private LocationMode mLocationMode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 在使用SDK各组件之前初始化context信息，传入ApplicationContext
		// 注意该方法要再setContentView方法之前实现
		SDKInitializer.initialize(getApplicationContext());

		setContentView(R.layout.activity_baidumap);

		this.context = this;

		mIntent = getIntent();
		if (mIntent.hasExtra("ExpressId")) {
			String expressId = mIntent.getStringExtra("ExpressId");
			mLoader = new ExpressHistoryLoader(this, this);
			mLoader.getHistory(expressId);
		}

		initView();
		// 初始化定位
		initLocation();

	}

	private void initLocation() {

		mLocationMode = LocationMode.NORMAL;
		mLocationClient = new LocationClient(this);
		mLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mLocationListener);

		LocationClientOption option = new LocationClientOption();
		option.setCoorType("bd09ll");
		option.setIsNeedAddress(true);
		option.setOpenGps(true);
		option.setScanSpan(10000);
		mLocationClient.setLocOption(option);
		// 初始化图标
		mIconLocation = BitmapDescriptorFactory
				.fromResource(R.drawable.navi_map_gps_locked);

	}

	private void initView() {
		mMapView = (MapView) findViewById(R.id.id_bmapView);
		mBaiduMap = mMapView.getMap();
		MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
		mBaiduMap.setMapStatus(msu);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
		mMapView.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
		// 开启定位
		mBaiduMap.setMyLocationEnabled(true);
		if (!mLocationClient.isStarted())
			mLocationClient.start();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mMapView.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();

		// 停止定位
		mBaiduMap.setMyLocationEnabled(false);
		mLocationClient.stop();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mMapView.onDestroy();
	}

	private class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {

			MyLocationData data = new MyLocationData.Builder()//
					.direction(mCurrentX)//
					.accuracy(location.getRadius())//
					.latitude(location.getLatitude())//
					.longitude(location.getLongitude())//
					.build();
			mBaiduMap.setMyLocationData(data);
			// 设置自定义图标
			MyLocationConfiguration config = new MyLocationConfiguration(
					mLocationMode, true, mIconLocation);
			mBaiduMap.setMyLocationConfigeration(config);

			if (isFirstIn) {
				LatLng latLng = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
				mBaiduMap.animateMapStatus(msu);
				isFirstIn = false;

				Toast.makeText(context, location.getAddrStr(),
						Toast.LENGTH_SHORT).show();
			}

		}
	}

	/**
	 * 返回或保存时调用的方法
	 */
	@Override
	public void onBackPressed() {

		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		finish();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			finish();
		}
		return false;
	}

	@Override
	public List<HistoryGist> getData() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setData(List<HistoryGist> data) {
		historyGists = data;
		latLngPolygon = new ArrayList<LatLng>();
		for (HistoryGist h : historyGists) {
			if (h != null) {

				latitude = h.getX();
				longtitude = h.getY();
				// 绘制折线图层
				LatLng latlng = new LatLng(latitude, longtitude);
				latLngPolygon.add(latlng);

				// 将每个点进行标记
				switch (h.getState())
					{
					case HistoryGist.STATE.HISTORYGIST_RECEIVE: {
						// 揽收的网店有绿色图标
						BitmapDescriptor bitmap2 = BitmapDescriptorFactory
								.fromResource(R.drawable.location_arrows);
						OverlayOptions options2 = new MarkerOptions().position(
								latlng).icon(bitmap2);
						mBaiduMap.addOverlay(options2);
						break;
					}
					case HistoryGist.STATE.HISTORYGIST_TRANS: {
						// 中转图标有绿色
						BitmapDescriptor bitmap2 = BitmapDescriptorFactory
								.fromResource(R.drawable.location_arrows);
						OverlayOptions options2 = new MarkerOptions().position(
								latlng).icon(bitmap2);
						mBaiduMap.addOverlay(options2);
						break;
					}
					case HistoryGist.STATE.HISTORYGIST_TARGET: {
						// 终点有红色图标
						BitmapDescriptor bitmap2 = BitmapDescriptorFactory
								.fromResource(R.drawable.maker);
						OverlayOptions options2 = new MarkerOptions().position(
								latlng).icon(bitmap2);
						mBaiduMap.addOverlay(options2);
						break;
					}
					}

			}
		}
	}

	@Override
	public void notifyDataSetChanged() {
		try {
			PolylineOptions po = new PolylineOptions().color(
					getResources().getColor(R.color.darkgreen)).points(
					latLngPolygon);
			mBaiduMap.addOverlay(po);
		} catch (Exception e) {
			Toast.makeText(this, "刚刚揽收过的包裹没有历史消息:)", Toast.LENGTH_SHORT).show();
			//Intent intent = new Intent(this, MainActivity.class);
			//startActivity(intent);
		}
	}

}
